<template>
  <div class="app-container">
    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="催收编号:">
          <el-input v-model="queryParams.code" clearable placeholder="请输入" maxlength="30"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="客户名称:">
          <el-input v-model="queryParams.customerName" clearable placeholder="请输入" maxlength="30"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="处理人:">
          <el-input v-model="queryParams.processedByNames" clearable placeholder="请输入" maxlength="30"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="创建时间:">
          <el-date-picker v-model="foreWarningTime" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="催收进度:">
          <el-select v-model="queryParams.collectionProgress" clearable>
            <template v-for="dict in dict.type.collection_progress">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="客户等级:">
          <el-select v-model="queryParams.customerLevel" clearable>
            <template v-for="dict in dict.type.customer_level">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="客户来源:">
          <el-select v-model="queryParams.customerSource" clearable>
            <template v-for="dict in dict.type.customer_source">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
    </SearchContent>
    <div class="card-wrap flex-column justify-end card-padding">
      <div style="display: flex;justify-content: start;align-items: center;">
        <div style="margin-left: 10px; border: 1px solid #ccc;font-size: 15px; color: #1890ff; width: 160px;height: 35px;line-height: 35px;text-align: center;border-radius: 10px;">
          <span style="color: #606266;">预计明日回款:</span>
          <span>{{ dataObj.paymentIsExpectedTomorrow }}</span>
        </div>
        <div style="margin-left: 10px;border: 1px solid #ccc;font-size: 15px; color: #1890ff; width: 160px;height: 35px;line-height: 35px;text-align: center;border-radius: 10px;">
          <span style="color: #606266;">预计今日回款:</span>
          <span>{{ dataObj.paymentIsExpectedToday }}</span>
        </div>
        <div style="margin-left: 10px;border: 1px solid #ccc;font-size: 15px; color: #1890ff; width: 160px;height: 35px;line-height: 35px;text-align: center;border-radius: 10px;">
          <span style="color: #606266;">昨日处理催收:</span>
          <span>{{ dataObj.collectionsWereProcessedYesterday }}</span>
        </div>
        <div style="margin-left: 10px;border: 1px solid #ccc;font-size: 15px; color: #1890ff; width: 160px;height: 35px;line-height: 35px;text-align: center;border-radius: 10px;">
          <span style="color: #606266;">今日处理催收:</span>
          <span>{{ dataObj.collectionsAreProcessedToday }}</span>
        </div>
        <div style="margin-left: 10px;border: 1px solid #ccc;font-size: 15px; color: #1890ff; width: 160px;height: 35px;line-height: 35px;text-align: center;border-radius: 10px;">
          <span style="color: #606266;">超时未处理:</span>
          <span>{{ dataObj.timeoutOutstanding }}</span>
        </div>
        <div style="margin-left: 10px;border: 1px solid #ccc;font-size: 15px; color: #1890ff; width: 160px;height: 35px;line-height: 35px;text-align: center;border-radius: 10px;">
          <span style="color: #606266;">催收无结果:</span>
          <span>{{ dataObj.noResultOfCollection }}</span>
        </div>
      </div>

    </div>
    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
        <el-button type="primary" size="mini" @click="btn(1)" v-hasPermi="['collectionModule:collectionManage:untreated']">工单未处理预警配置</el-button>
        <el-button type="primary" size="mini" @click="btn(2)" v-hasPermi="['collectionModule:collectionManage:fruitless']">无结果预警</el-button>
        <el-button type="primary" size="mini" @click="handleExport" v-hasPermi="['collectionModule:collectionManage:export']">导出</el-button>
      </div>

      <table-page :loading="loading" :dataList="dataList" border :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @setSizeCurrent="getList">
        <!-- 操作插槽 -->
        <template slot="tableColAc">
          <el-table-column label="操作" fixed width="340" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="text" v-hasPermi="['collectionModule:collectionManage:view']" @click="btn(3,scope.row)">查看</el-button>
              <el-button v-if="scope.row.collectionProgress ==1 || scope.row.collectionProgress ==2 ||scope.row.collectionProgress ==3" type="text" v-hasPermi="['collectionModule:collectionManage:strategy']" @click="btn(4,scope.row)">
                调整策略
              </el-button>
              <el-button type="text" v-if="scope.row.canWriteOffApplication" v-hasPermi="['collectionModule:collectionManage:Apply']" @click="btn(5,scope.row)">申请销账</el-button>
              <el-button type="text" v-if="(scope.row.collectionProgress ==1 || scope.row.collectionProgress ==2 ||scope.row.collectionProgress ==3) && scope.row.isSuspend ==0" v-hasPermi="['collectionModule:collectionManage:putOff']" @click="btn(6,scope.row)">暂缓</el-button>
              <el-button type="text" v-if="(scope.row.collectionProgress ==1 || scope.row.collectionProgress ==2 ||scope.row.collectionProgress ==3) && scope.row.isSuspend ==1" v-hasPermi="['collectionModule:collectionManage:putON']" @click="btn(9,scope.row)">激活</el-button>
              <el-button type="text" v-if="scope.row.collectionProgress ==1 || scope.row.collectionProgress ==2 ||scope.row.collectionProgress ==3" v-hasPermi="['collectionModule:collectionManage:reassignment']" @click="btn(7,scope.row)">改派</el-button>
              <el-button type="text" v-if="scope.row.completionOfAction == 1" v-hasPermi="['collectionModule:collectionManage:settlement']" @click="btn(8,scope.row)">手动结清</el-button>
            </template>
          </el-table-column>
        </template>
        <!-- 普通列插槽 -->
        <template slot="tableCol">
          <el-table-column label="催收编号" fixed align="center" prop="code" min-width="200px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="blue">{{scope.row.code}}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户名称" align="center" prop="customerName" min-width="180px" show-overflow-tooltip />
          <el-table-column label="客户等级" align="center" prop="customerLevel">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.customer_level" :value="scope.row.customerLevel" />
            </template>
          </el-table-column>
          <el-table-column label="客户来源" align="center" prop="customerSource">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.customer_source" :value="scope.row.customerSource" />
            </template>
          </el-table-column>
          <el-table-column label="累计应收金额" align="center" prop="totalReceivableAmount" min-width="120px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ format_thousand(scope.row.totalReceivableAmount)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="累计已收金额" align="center" prop="totalReceivedAmount" min-width="120px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ format_thousand(scope.row.totalReceivedAmount)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="累计待收金额" align="center" prop="totalToBeReceived" min-width="120px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ format_thousand(scope.row.totalToBeReceived)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="累计销账金额" align="center" prop="totalWriteOffAmount" min-width="120px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ format_thousand(scope.row.totalWriteOffAmount)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="本月回款金额" align="center" prop="amountOfThisMonth" min-width="120px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ format_thousand(scope.row.amountOfThisMonth)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="今日回款金额" align="center" prop="amountOfToDay" min-width="120px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ format_thousand(scope.row.amountOfToDay)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="催收进度" align="center" prop="collectionProgress" min-width="150px" show-overflow-tooltip>
            <template slot-scope="scope">
              <div style="display: flex;justify-content: start;align-items: center;">
                <dict-tag :options="dict.type.collection_progress" :value="scope.row.collectionProgress" style="margin-left: 40px;" />
                <span v-if="scope.row.isSuspend==1" style="color: #1890ff;"> ({{ scope.row.isSuspend==0?'未暂缓':'已暂缓' }})</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="处理人" align="center" prop="processedByNames" min-width="180px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.processedByNames }}</span>
              <span v-if="scope.row.reassignment ==1" style="color: #1890ff;"> ({{ scope.row.reassignment==0?'':'已改派' }})</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" min-width="150px" show-overflow-tooltip />
        </template>
      </table-page>
    </div>

    <!-- 添加或修改测试单表对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body class="form-dialog" :width="width">
      <div style="width: 90%; margin: 0 auto;">
        <!-- 工单未处理预警配置 -->
        <el-form ref="formDig" label-position="right" :model="formDig" label-width="160px" :rules="rules">
          <el-form-item v-if="type ==1 || type ==2" :label="type == 1?'未处理预警配置:':'催收无结果预警配置:'" prop="requires">
            <el-radio-group v-model="formDig.requires">
              <el-radio :label="2">无需预警</el-radio>
              <el-radio :label="1">
                <span v-if="type==2">连续</span>
                <el-input-number style="margin-left:5px;margin-right: 5px;" v-model="formDig.param" :disabled="formDig.requires ==2" controls-position="right" :min="0" :max="999999999" />
                <span v-if="type ==1">天未处理</span>
                <span v-else>次无结果</span>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 调整策略 -->
          <el-form-item v-if="type ==4" label="调整策略:" prop="collectionStrategy">
            <el-radio-group v-model="formDig.collectionStrategy">
              <el-radio v-for="item in dict.type.collection_strategy" :label="item.value" :key="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 暂缓催收 || 手动结清 -->
          <el-form-item v-if="type ==8" label="待收金额:">
            <span>{{formDig.totalToBeReceived}}</span>
          </el-form-item>
          <el-form-item v-if="type ==8" label="结清金额:">
            <span>{{formDig.totalToBeReceived}}</span>
          </el-form-item>
          <el-form-item v-if="type ==8" label="收款时间:" prop="collectionTime">
            <el-date-picker v-model="formDig.collectionTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" style="width: 40%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item v-if="type ==6 ||type ==8 || type==9" label="说明:" prop="remark">
            <el-input type="textarea" placeholder="请输入说明内容" v-model="formDig.remark" maxlength="500" :rows="5" show-word-limit>
            </el-input>
          </el-form-item>
          <el-form-item v-if="type ==6||type ==8  || type==9" label="附件:" prop="attachments">
            <ImageCommon :up-type="2" info="选择附件" :limit="5" v-model="formDig.attachments" isShowTip :fileSize="30" :fileType="['png/jpg/jpeg/pdf/doc/docx/excel']"></ImageCommon>
          </el-form-item>
          <!-- 选择人员 -->
          <div style="display: flex;justify-content: space-between;align-items: center;" v-if="type ==7">
            <el-form-item label="用户名称:" label-width="80px">
              <el-input v-model="queryParamsDig.nickName" clearable placeholder="请输入用户名称" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="手机号码:" label-width="80px" style="margin-left: 20px;">
              <el-input v-model="queryParamsDig.phonenumber" clearable maxlength="11" style="width: 100%;" placeholder="请输入手机号码" @input="queryParamsDig.phonenumber=queryParamsDig.phonenumber.replace(/^0|[^0-9]/g, '')"></el-input>
            </el-form-item>
            <div style="text-align: right;margin-top: -15px;margin-left: 50px;">
              <el-button size="mini" @click="resetQueryDig">重 置</el-button>
              <el-button size="mini" type="primary" @click="handleQueryDig">查 询</el-button>
            </div>
          </div>
          <table-page ref="el-table" v-if="type ==7" rowKey="userId" :isSelect="true" @selectionChange="handleSelectionChange" :loading="loadingTable" :dataList="dataListTable" border :total="totalTable" :page.sync="queryParamsDig.pageNum" :limit.sync="queryParamsDig.pageSize" @setSizeCurrent="getListTable">
            <!-- 普通列插槽 -->
            <template slot="tableCol">
              <el-table-column label="用户名称" align="center" prop="nickName" />
              <el-table-column label="手机号码" align="center" prop="phonenumber" />
              <el-table-column label="组织名称" align="center" prop="dept.allDeptName" min-width="140px" show-overflow-tooltip />
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <span>{{scope.row.status ==0?'正常':'停用'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" width="150" />
            </template>
          </table-page>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="cancelDig">取消</el-button>
        <el-button type="primary" @click="submitForm">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SearchContent from "@/components/SearchContent/index.vue";
import { statisticsDetail, collectionConfig, saveCollectionConfig, getUseList, getCollectionManageList, sendDispatchRecord, sendManualSettlement, sendStrategyAdjustment, sendSuspendActivate } from "@/api/collectionModule";
export default {
  name: 'CollectionManage',
  components: {
    SearchContent,
  },
  dicts: ["collection_progress", 'customer_level', 'collection_strategy', 'customer_source'],
  data() {
    return {
      dataObj: {},
      width: '65%',
      title: '',
      loadingTable: false,
      dataListTable: [],
      totalTable: 0,
      rules: {
        requires: [
          { required: true, message: "请选择预警配置", trigger: "change" },
        ],
        collectionStrategy: [
          { required: true, message: "请选择调整策略", trigger: "change" },
        ],
        remark: [
          { required: true, message: "请输入说明", trigger: "blur" },
        ],
        collectionTime: [
          { required: true, message: "请选择收款时间", trigger: "blur" },
        ],
      },
      foreWarningTime: [],
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParamsDig: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dataList: [],
      // 表单参数
      formDig: { requires: 1 },
      type: null,
      processedByNames: [],
      processedByIds: [],
      multipleSelection: [],
    };
  },
  watch: {
    dataListTable: {
      handler(Val) {
        this.$nextTick(() => {
          if (Val.length > 0) {
            Val.forEach((v) => {
              this.processedByIds.forEach((j) => {
                if (
                  Number(v.userId) == Number(j)
                ) {
                  this.$refs['el-table']?.table_toggleRowSelection(v, true)
                }
              });
            });
          }
        })
      },
      immediate: true, // 立即生效
      deep: true  //监听对象或数组的时候，要用到深度监听
    },
  },
  created() {
    this.getList();
    this.statisticsDetail()
  },
  methods: {
    statisticsDetail() {
      statisticsDetail(this.queryParams).then(res => {
        if (res.code == '200') {
          this.dataObj = res.data
        }
      })
    },
    // 选择人员接口
    async getListTable() {
      this.loadingTable = true;
      try {
        let res = await getUseList(this.queryParamsDig)
        const { rows, total } = res;
        this.dataListTable = rows;
        this.totalTable = total;
        this.loadingTable = false;
      } catch (error) {

      }
    },
    // 多选按钮
    handleSelectionChange(val) {
      console.log(val, '00000');
      this.multipleSelection = val
      // this.processedByIds = this.multipleSelection.map(v => v.userId)
      this.processedByNames = this.multipleSelection.map(v => v.nickName)
    },
    cancelDig() { this.open = false },
    // 导出
    handleExport() {
      this.download('/collectionManage/collectionManage/export', {
        ...this.queryParams
      }, `催收列表_${new Date().getTime()}.xlsx`)
    },
    /** 预警配置 */
    btn(type, row) {
      this.formDig.param = null
      this.type = type
      this.open = true
      this.$set(this, 'formDig', {})
      this.$nextTick(() => {
        this.$refs["formDig"]?.clearValidate()
      })
      if (type == 1) {
        this.width = '35%'
        this.title = '工单未处理预警配置'
        collectionConfig(2).then(res => {
          this.formDig = res.data[0]
        })
      } else if (type == 2) {
        this.width = '35%'
        this.title = '催收无结果预警配置'
        collectionConfig(3).then(res => {
          this.formDig = res.data[0]
        })
      } else if (type == 4) {
        console.log(row);
        this.width = '35%'
        this.title = '调整策略'
        this.$set(this.formDig, 'collectionStrategy', row.collectionProgress.toString())
        this.$set(this.formDig, 'manageId', row.id)
      } else if (type == 6) {
        this.width = '55%'
        this.title = '暂缓催收'
        this.$set(this.formDig, 'manageId', row.id)
        this.$set(this.formDig, 'operation', 1)
      } else if (type == 9) {
        this.width = '55%'
        this.title = '激活催收'
        this.$set(this.formDig, 'manageId', row.id)
        this.$set(this.formDig, 'operation', 0)
      } else if (type == 7) {
        this.$refs['el-table']?.table_clearSelection()
        this.queryParamsDig.pageNum = 1
        this.width = '65%'
        this.title = '选择人员'
        this.title = '选择人员'
        this.formDig.manageId = row.id
        this.processedByIds = row.processedByIds.split(',')
        this.processedByNames = row.processedByNames.split(',')
        this.getListTable()
      } else if (type == 8) {
        this.width = '55%'
        this.title = '手动结清'
        this.$set(this.formDig, 'manageId', row.id)
        this.$set(this.formDig, 'totalToBeReceived', row.totalToBeReceived)
      } else if (type == 3) {
        // 查看详情
        this.open = false
        this._toPage({
          path: "/collectionModule/collectionWarning/initiateACollectionDetail",
          name: "InitiateACollectionDetail",
          query: {
            type: 'detail',
            beFrom: 'CollectionManage',
            id: row.id
          }
        });
      } else if (type == 5) {
        this.open = false
        this._toPage({
          path: "/collectionModule/collectionManage/applyForWriteOff",
          name: "ApplyForWriteOff",
          query: {
            type: 'CollectionManage',
            beFrom: 'CollectionManage',
            id: row.id
          }
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDig"].validate((valid) => {
        if (valid) {
          if (this.type == 1 || this.type == 2) {
            if (this.formDig.requires == 1 || this.formDig.requires == 2) {
              if (this.formDig.param) {
                // 调取接口
                saveCollectionConfig(this.formDig).then(res => {
                  this.$message.success('修改成功')
                  this.open = false;
                })
                this.open = false
              } else {
                this.open = true
                if (this.type == 1) {
                  this.$message.error('请输入天数')
                } else {
                  this.$message.error('请输入次数')
                }
              }
            } else {
              this.open = false
            }
          } else if (this.type == 4) {
            // 接口
            sendStrategyAdjustment(this.formDig).then(res => {
              this.$message.success('修改成功')
              this.open = false;
              this.getList();
              this.statisticsDetail()
            })
          } else if (this.type == 6 || this.type == 9) {
            // 接口
            sendSuspendActivate(this.formDig).then(res => {
              if (this.formDig.operation == 1) {
                this.$message.success('暂缓成功')
              } else {
                this.$message.success('激活成功')
              }
              this.open = false;
              this.getList();
              this.statisticsDetail()
            })
          } else if (this.type == 8) {
            // 接口
            sendManualSettlement(this.formDig).then(res => {
              this.$message.success('手动结清成功')
              this.open = false;
              this.getList();
              this.statisticsDetail()
            })
          } else if (this.type == 7) {
            let formDig = {
              ...this.formDig,
              processedByIds: this.multipleSelection.map(v => v.userId).join(','),
              processedByNames: this.processedByNames.join(','),
            }
            // 接口
            sendDispatchRecord(formDig).then(res => {
              this.$message.success('改派成功')
              this.open = false;
              this.getList();
              this.statisticsDetail()
            })
          }
        }
      });
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true;
      getCollectionManageList(this.queryParams).then((res) => {
        if (res.code == "200") {
          const { rows, total } = res;
          this.dataList = rows;
          this.total = total;
          this.loading = false;
        }
      });
    },
    // 清空校验
    clearCheck() {
      this.$refs["form"] && this.$refs["form"].resetFields();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.clearCheck()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.startTime = this.foreWarningTime[0]
      this.queryParams.endTime = this.foreWarningTime[1]
      this.getList();
      this.statisticsDetail()
    },
    handleQueryDig() {
      this.getListTable()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }
      this.foreWarningTime = []
      this.handleQuery();
    },
    resetQueryDig() {
      this.queryParamsDig = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getListTable()
    },
  },
};
</script>
<style lang="scss" scoped>
.pagination-container {
  padding: 0 20px 50px !important;
}
.blue {
  color: #1890ff !important;
  cursor: pointer;
}
</style>
